// 主应用JavaScript文件

// DOM加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 初始化应用
    initApp();
    
    // 绑定导航事件
    bindNavigationEvents();
    
    // 绑定表单事件
    bindFormEvents();
});

// 初始化应用
function initApp() {
    console.log('FinanceApp initialized');
    
    // 检查用户登录状态
    checkUserStatus();
    
    // 初始化页面
    initPage();
}

// 检查用户状态
function checkUserStatus() {
    // 这里应该检查JWT token或session
    // 暂时使用localStorage模拟
    const token = localStorage.getItem('authToken');
    
    if (token) {
        // 用户已登录
        showLoggedInState();
        // 加载最近账单
        loadRecentBills();
    } else {
        // 用户未登录
        showLoggedOutState();
    }
    
    // 更新首页内容
    updateHomePageContent(!!token);
}

// 显示已登录状态
function showLoggedInState() {
    // 显示用户相关功能
    document.querySelectorAll('.auth-required').forEach(el => {
        el.style.display = 'block';
    });
    
    // 隐藏登录相关功能
    document.querySelectorAll('.auth-not-required').forEach(el => {
        el.style.display = 'none';
    });
}

// 显示未登录状态
function showLoggedOutState() {
    // 隐藏用户相关功能
    document.querySelectorAll('.auth-required').forEach(el => {
        el.style.display = 'none';
    });
    
    // 显示登录相关功能
    document.querySelectorAll('.auth-not-required').forEach(el => {
        el.style.display = 'block';
    });
}

// 更新首页内容
function updateHomePageContent(isLoggedIn) {
    const guestContent = document.getElementById('guestHomeContent');
    const userContent = document.getElementById('userHomeContent');
    
    if (isLoggedIn) {
        // 显示用户内容，隐藏访客内容
        if (guestContent) guestContent.style.display = 'none';
        if (userContent) {
            userContent.style.display = 'block';
            // 更新用户名
            const username = localStorage.getItem('username');
            if (username) {
                const welcomeElement = document.getElementById('welcomeUsername');
                if (welcomeElement) {
                    welcomeElement.textContent = username;
                }
            }
            
            // 加载最近账单
            loadRecentBills();
        }
    } else {
        // 显示访客内容，隐藏用户内容
        if (guestContent) guestContent.style.display = 'block';
        if (userContent) userContent.style.display = 'none';
    }
}

// 绑定导航事件
function bindNavigationEvents() {
    const navLinks = document.querySelectorAll('nav a[data-target]');
    
    navLinks.forEach(link => {
        link.addEventListener('click', function(e) {
            e.preventDefault();
            const target = this.getAttribute('data-target');
            navigateTo(target);
        });
    });
}

// 页面导航
function navigateTo(page) {
    // 隐藏所有页面
    document.querySelectorAll('.page').forEach(pageEl => {
        pageEl.style.display = 'none';
    });
    
    // 显示目标页面
    const targetPage = document.getElementById(page + 'Page');
    if (targetPage) {
        targetPage.style.display = 'block';
        
        // 执行页面特定的初始化
        if (typeof window[page + 'PageInit'] === 'function') {
            window[page + 'PageInit']();
        }
        
        // 如果导航到首页，根据登录状态更新内容
        if (page === 'home') {
            const token = localStorage.getItem('authToken');
            updateHomePageContent(!!token);
        }
        
        // 如果导航到仪表板，加载相关数据
        if (page === 'dashboard') {
            loadDashboardData();
        }
    }
}

// 仪表板页面初始化
function dashboardPageInit() {
    loadDashboardData();
}

// 加载仪表板数据
async function loadDashboardData() {
    try {
        const token = localStorage.getItem('authToken');
        if (!token) {
            console.error('用户未登录');
            return;
        }
        
        // 获取账单统计数据
        const statsResponse = await fetch('http://localhost:3003/api/bills/stats', {
            method: 'GET',
            headers: {
                'Authorization': `Bearer ${token}`,
                'Content-Type': 'application/json'
            }
        });
        
        if (!statsResponse.ok) {
            throw new Error(`HTTP error! status: ${statsResponse.status}`);
        }
        
        const statsData = await statsResponse.json();
        
        // 渲染仪表板数据
        renderDashboard(statsData);
    } catch (error) {
        console.error('加载仪表板数据失败:', error);
    }
}

// 渲染仪表板
function renderDashboard(data) {
    const { summary } = data;
    
    // 更新仪表板页面的数据
    const dashboardPage = document.getElementById('dashboardPage');
    if (dashboardPage) {
        // 更新总收入
        const incomeElements = dashboardPage.querySelectorAll('.dashboard .card.neon-border:nth-child(1) p');
        if (incomeElements.length > 0) {
            incomeElements[0].textContent = `¥${summary.total_income.toFixed(2)}`;
        }
        
        // 更新总支出
        const expenseElements = dashboardPage.querySelectorAll('.dashboard .card.neon-border:nth-child(2) p');
        if (expenseElements.length > 0) {
            expenseElements[0].textContent = `¥${summary.total_expense.toFixed(2)}`;
        }
        
        // 更新结余
        const balanceElements = dashboardPage.querySelectorAll('.dashboard .card.neon-accent:nth-child(3) p');
        if (balanceElements.length > 0) {
            balanceElements[0].textContent = `¥${summary.net_income.toFixed(2)}`;
        }
    }
    
    // 更新首页的本月概览
    const homePage = document.getElementById('homePage');
    if (homePage) {
        // 更新总收入
        const incomeElements = homePage.querySelectorAll('#userHomeContent .dashboard .card.neon-border:nth-child(1) p');
        if (incomeElements.length > 0) {
            incomeElements[0].textContent = `¥${summary.total_income.toFixed(2)}`;
        }
        
        // 更新总支出
        const expenseElements = homePage.querySelectorAll('#userHomeContent .dashboard .card.neon-border:nth-child(2) p');
        if (expenseElements.length > 0) {
            expenseElements[0].textContent = `¥${summary.total_expense.toFixed(2)}`;
        }
        
        // 更新结余
        const balanceElements = homePage.querySelectorAll('#userHomeContent .dashboard .card.neon-accent:nth-child(3) p');
        if (balanceElements.length > 0) {
            balanceElements[0].textContent = `¥${summary.net_income.toFixed(2)}`;
        }
    }
}

// 账单页面初始化
function billsPageInit() {
    // 设置默认日期为今天
    const today = new Date().toISOString().split('T')[0];
    const dateInput = document.getElementById('billDate');
    if (dateInput) {
        dateInput.value = today;
    }
    
    // 绑定重置按钮事件
    const resetBtn = document.getElementById('resetBillForm');
    if (resetBtn) {
        resetBtn.addEventListener('click', function() {
            const billForm = document.getElementById('billForm');
            if (billForm) {
                billForm.reset();
                dateInput.value = today;
                
                // 恢复表单提交处理程序
                billForm.onsubmit = null;
                billForm.addEventListener('submit', function(e) {
                    if (window.billsComponent) {
                        window.billsComponent.handleBillSubmit(e);
                    }
                });
            }
        });
    }
    
    // 加载账单列表
    if (window.billsComponent) {
        window.billsComponent.loadBills();
    }
}

// 绑定表单事件
function bindFormEvents() {
    // 登录表单
    const loginForm = document.getElementById('loginForm');
    if (loginForm) {
        loginForm.addEventListener('submit', handleLogin);
    }
    
    // 注册表单
    const registerForm = document.getElementById('registerForm');
    if (registerForm) {
        registerForm.addEventListener('submit', handleRegister);
    }
    
    // 记账表单
    const billForm = document.getElementById('billForm');
    if (billForm) {
        billForm.addEventListener('submit', handleBillSubmit);
    }
}

// 处理登录
async function handleLogin(e) {
    e.preventDefault();
    
    const phone = document.getElementById('loginPhone').value;
    const password = document.getElementById('loginPassword').value;
    
    try {
        // 调用后端API
        const response = await fetch('http://localhost:3003/api/users/login', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ phone, password })
        });
        
        const data = await response.json();
        
        if (response.ok) {
            // 保存token
            localStorage.setItem('authToken', data.token);
            
            // 更新UI
            showLoggedInState();
            
            // 更新首页内容
            updateHomePageContent(true);
            
            // 加载最近账单
            loadRecentBills();
            
            // 跳转到仪表板
            navigateTo('dashboard');
            
            showMessage('登录成功', 'success');
        } else {
            showMessage(data.error || '登录失败', 'error');
        }
    } catch (error) {
        showMessage('网络错误，请稍后重试', 'error');
        console.error('Login error:', error);
    }
}

// 处理注册
async function handleRegister(e) {
    e.preventDefault();
    
    const username = document.getElementById('registerUsername').value;
    const phone = document.getElementById('registerPhone').value;
    const password = document.getElementById('registerPassword').value;
    const confirmPassword = document.getElementById('registerConfirmPassword').value;
    
    // 简单验证
    if (password !== confirmPassword) {
        showMessage('两次输入的密码不一致', 'error');
        return;
    }
    
    try {
        // 调用后端API
        const response = await fetch('http://localhost:3003/api/users/register', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ username, phone, password })
        });
        
        const data = await response.json();
        
        if (response.ok) {
            showMessage('注册成功，请登录', 'success');
            // 切换到登录页面
            navigateTo('login');
        } else {
            showMessage(data.error || '注册失败', 'error');
        }
    } catch (error) {
        showMessage('网络错误，请稍后重试', 'error');
        console.error('Register error:', error);
    }
}

// 处理记账提交
async function handleBillSubmit(e) {
    e.preventDefault();
    
    const formData = new FormData(e.target);
    const billData = {
        type: formData.get('type'),
        amount: parseFloat(formData.get('amount')),
        category_id: formData.get('categoryId'),
        title: formData.get('title'),
        description: formData.get('description'),
        bill_date: formData.get('date')
    };
    
    // 验证必填字段
    if (!billData.title) {
        showMessage('请输入标题', 'error');
        return;
    }
    
    if (!billData.category_id) {
        showMessage('请选择分类', 'error');
        return;
    }
    
    if (!billData.bill_date) {
        showMessage('请选择日期', 'error');
        return;
    }
    
    try {
        // 使用账单组件提交账单
        if (window.billsComponent) {
            const result = await window.billsComponent.submitBill(billData);
            
            if (result.success) {
                showMessage('记账成功', 'success');
                // 重置表单
                e.target.reset();
                // 设置默认日期为今天
                const today = new Date().toISOString().split('T')[0];
                const dateInput = document.getElementById('billDate');
                if (dateInput) {
                    dateInput.value = today;
                }
            } else {
                showMessage(result.error, 'error');
            }
        } else {
            // 回退到原来的实现
            const token = localStorage.getItem('authToken');
            
            // 调用后端API
            const response = await fetch('http://localhost:3003/api/bills', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                },
                body: JSON.stringify(billData)
            });
            
            const data = await response.json();
            
            if (response.ok) {
                showMessage('记账成功', 'success');
                // 重置表单
                e.target.reset();
                // 刷新账单列表
                if (typeof window.loadBills === 'function') {
                    window.loadBills();
                }
                // 重新加载最近账单
                loadRecentBills();
            } else {
                showMessage(data.error || '记账失败', 'error');
            }
        }
    } catch (error) {
        showMessage('网络错误，请稍后重试', 'error');
        console.error('Bill submit error:', error);
    }
}

// 获取最近账单
async function loadRecentBills() {
    try {
        const token = localStorage.getItem('authToken');
        if (!token) {
            return;
        }
        
        const response = await fetch('http://localhost:3003/api/bills?limit=5', {
            method: 'GET',
            headers: {
                'Authorization': `Bearer ${token}`,
                'Content-Type': 'application/json'
            }
        });
        
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        const data = await response.json();
        const bills = data.bills || [];
        
        // 渲染最近账单
        renderRecentBills(bills);
    } catch (error) {
        console.error('加载最近账单失败:', error);
    }
}

// 渲染最近账单
function renderRecentBills(bills) {
    const recentBillsContainer = document.getElementById('recentBills');
    if (!recentBillsContainer) return;
    
    if (!bills || bills.length === 0) {
        recentBillsContainer.innerHTML = '<p>暂无账单记录</p>';
        return;
    }
    
    let billsHtml = '';
    bills.forEach(bill => {
        const date = new Date(bill.bill_date).toLocaleDateString('zh-CN');
        const amount = parseFloat(bill.amount).toFixed(2);
        const isIncome = bill.type === 'income';
        const amountColor = isIncome ? '#0f0' : '#f00';
        const amountSign = isIncome ? '+' : '-';
        
        billsHtml += `
            <div style="display: flex; justify-content: space-between; align-items: center; padding: 10px 0; border-bottom: 1px solid rgba(255,255,255,0.1);">
                <div>
                    <h4 style="margin: 0;">${bill.title}</h4>
                    <p style="margin: 5px 0 0 0; font-size: 0.9rem; color: #aaa;">${date}</p>
                </div>
                <div style="text-align: right;">
                    <p style="margin: 0; font-size: 1.1rem; color: ${amountColor};">${amountSign}¥${amount}</p>
                    <p style="margin: 5px 0 0 0; font-size: 0.9rem; color: #aaa;">${bill.category_name || '未分类'}</p>
                </div>
            </div>
        `;
    });
    
    recentBillsContainer.innerHTML = billsHtml;
}

// 显示消息
function showMessage(message, type) {
    // 创建消息元素
    const messageEl = document.createElement('div');
    messageEl.className = `message message-${type}`;
    messageEl.textContent = message;
    
    // 添加样式
    Object.assign(messageEl.style, {
        position: 'fixed',
        top: '20px',
        right: '20px',
        padding: '15px 20px',
        borderRadius: '5px',
        color: 'white',
        fontWeight: 'bold',
        zIndex: '1000',
        boxShadow: '0 2px 10px rgba(0,0,0,0.3)'
    });
    
    if (type === 'success') {
        messageEl.style.backgroundColor = '#4CAF50';
    } else {
        messageEl.style.backgroundColor = '#F44336';
    }
    
    // 添加到页面
    document.body.appendChild(messageEl);
    
    // 3秒后移除
    setTimeout(() => {
        if (messageEl.parentNode) {
            messageEl.parentNode.removeChild(messageEl);
        }
    }, 3000);
}

// 初始化页面
function initPage() {
    // 设置默认日期为今天
    const today = new Date().toISOString().split('T')[0];
    const dateInput = document.getElementById('billDate');
    if (dateInput) {
        dateInput.value = today;
    }
    
    // 检查用户登录状态，如果已登录则显示仪表板，否则显示首页
    const token = localStorage.getItem('authToken');
    if (token) {
        // 更新首页内容
        updateHomePageContent(true);
        // 加载最近账单
        loadRecentBills();
        navigateTo('dashboard');
    } else {
        navigateTo('home');
    }
}